package models

import (
	"fmt"
	"ginchat/utils"
	"github.com/jinzhu/gorm"
	"time"
)

type UserBasic struct {
	gorm.Model    //ID CreatedAt UpdatedAt DeletedAt
	Name          string
	PassWord      string
	Phone         string `valid:"matches(^1[3-9]{1}\\d{9}$)"`
	Email         string `valid:"email"`
	Identity      string //唯一标识
	ClientIp      string
	ClientPort    string
	Salt          string
	LoginTime     time.Time
	HeartbeatTime time.Time
	LoginOutTime  time.Time `gorm: "column:login_out_time" json:"login_out_time"`
	IsLogout      bool      //是否下线
	DeviceInfo    string    //设备信息
}

func (table *UserBasic) TableName() string {
	return "user_basic"
}

func FindUserByNameAndPwd(name string, password string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("name=? and password=?", name, password).First(&user)

	//token加密
	str := fmt.Sprintf("%d", time.Now().Unix()) //获取当前时间毫秒
	temp := utils.Md5Encode(str)                //直接对毫秒值加密
	utils.DB.Model(&user).Where("id=?", user.ID).
		Update("identity", temp) //将该用户的identity字段修改为时间戳加密串
	return user
}

// GetUserList 查找库中的10个用户
func GetUserList() []*UserBasic {

	data := make([]*UserBasic, 10)
	utils.DB.Find(&data)
	for _, v := range data {
		fmt.Println(v)
	}

	return data
}

// FindUserByName 根据用户名查找用户
func FindUserByName(name string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("name=?", name).First(&user)
	return user
}

// FindUserByPhone 根据用户名查找用户
func FindUserByPhone(phone string) *gorm.DB {
	user := UserBasic{}
	return utils.DB.Where("name=?", phone).First(&user)
}

// FindUserByEmail 根据Email查找用户
func FindUserByEmail(email string) *gorm.DB {
	user := UserBasic{}
	return utils.DB.Where("email=?", email).First(&user)
}

// CreateUser 添加用户
func CreateUser(user UserBasic) *gorm.DB {
	return utils.DB.Create(&user)
}

// DeleteUser 删除用户
func DeleteUser(user UserBasic) *gorm.DB {
	return utils.DB.Delete(&user)
}

// UpdateUser 修改用户
func UpdateUser(user UserBasic) *gorm.DB {
	return utils.DB.Model(&user).Update(
		UserBasic{ //表示要修改哪些字段
			Name:     user.Name,
			PassWord: user.PassWord,
			Phone:    user.Phone,
			Email:    user.Email,
		})
}
